package org.springblade.humanResource.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.humanResource.entity.Project;
import org.springblade.humanResource.entity.ZTUser;
import org.springblade.humanResource.mapper.HumanUserMapper;
import org.springblade.humanResource.mapper.ProjectMapper;
import org.springblade.humanResource.service.HumanUserService;
import org.springblade.oa.vo.BxVo;
import org.springblade.oa.vo.BxfymxVO;
import org.springblade.oa.vo.BxxcmxVO;
import org.springblade.system.entity.Dept;
import org.springblade.system.feign.ISysClient;
import org.springblade.system.user.entity.User;
import org.springblade.system.user.entity.UserInfo;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class HumanUserServiceImpl extends ServiceImpl<HumanUserMapper, ZTUser> implements HumanUserService {
	HumanUserMapper humanUserMapper;
	ISysClient sysClient;
	IUserClient userClient;
	ProjectMapper projectMapper;

	@Override
	public List<Map<String, Object>> getRYlist(Integer projectId) {
		return humanUserMapper.getRYlist(projectId);
	}

	/**
	 * 获取用户部门下拉框
	 *
	 * @param bladeUser
	 * @return
	 */
	@Override
	public List<HashMap<String, Object>> getDeptSelectByUser(BladeUser bladeUser) {
		String roles = bladeUser.getRoleId();
		String[] roleArr = roles.split(",");
		List<String> roleList = Arrays.asList(roleArr);
		List<HashMap<String, Object>> list = new ArrayList<>();
		List<Dept> deptList = null;
		String userDeptId = null;
		deptList = sysClient.getDeptList();
		R<UserInfo> userInfo = userClient.userInfo(Long.valueOf(bladeUser.getUserId()));
		if (userInfo.isSuccess()) {
			userDeptId = userInfo.getData().getUser().getDeptId();
		}
		HashMap<String, Object> deptMap;
		if (!deptList.isEmpty()) {
			for (Dept dept : deptList) {
				deptMap = new HashMap<>();
				deptMap.put("id", dept.getId());
				deptMap.put("name", dept.getDeptName());
				if (roleList.contains("8") && !roleList.contains("3")) {
					if (userDeptId.equals(deptMap.get("id").toString())) {
						list.add(deptMap);
					}
				} else if (roleList.contains("3") || roleList.contains("1") || roleList.contains("6") || roleList.contains("7")) {
					list.add(deptMap);
				}
			}
		}
		return list;
	}

	@Override
	public List<HashMap<String, Object>> getPersonnelByUser(BladeUser bladeUser, String projectId) {
		String roles = bladeUser.getRoleId();
		String[] roleArr = roles.split(",");
		List<String> roleList = Arrays.asList(roleArr);
		String userDeptId = null;
		String userAccount = null;
		R<UserInfo> userInfo = userClient.userInfo(Long.valueOf(bladeUser.getUserId()));
		if (userInfo.isSuccess()) {
			userDeptId = userInfo.getData().getUser().getDeptId();
			userAccount = userInfo.getData().getUser().getAccount();
		}
		HashMap map = new HashMap<String, Object>();
		//根据项目编号查询禅道项目Id
		if(projectId!=null && !projectId.equals("")){
			projectId = humanUserMapper.getProjectIdByCode(projectId);
		}
		map.put("projectId", projectId);
		if (roleList.contains("3") || roleList.contains("1") || roleList.contains("6") || roleList.contains("7")) {
		} else if ((roleList.contains("8") && !roleList.contains("3"))||roleList.contains("9")) {
			//部门经理
			if("4".equals(userDeptId)){
				userDeptId = "1";
			}else if("5".equals(userDeptId)){
				userDeptId = "2";
			}else if("6".equals(userDeptId)){
				userDeptId = "3";
			}else{
				userDeptId = "1";
			}
			map.put("dept", userDeptId);
		} else if (roleList.contains("9") && !roleList.contains("3") && !roleList.contains("8")) {
			map.put("account", userAccount);
		} else {
			map.put("account", userAccount);
		}
		List<HashMap<String, Object>> allPerson = humanUserMapper.getPersonnelByUser(map);
		//返回账号真实名称
		return allPerson;
	}
	@Override
	public HSSFWorkbook export(Map<String, Object> parm, HttpServletResponse response ){
//		项目列表
		List<Map<String,Object>> projectList = projectMapper.getProjectList(parm);//项目列表
//		人员列表
		List<ZTUser> userList = projectMapper.getUserList(parm);//人员列表
		Integer projectListSise = projectList.size();
		Integer userListSize = userList.size();
		HSSFWorkbook workbook = new HSSFWorkbook();
		workbook.setForceFormulaRecalculation(true);// 执行公式
		//生成一个表格，设置表格名称为"人力资源统计"
		HSSFSheet sheet = workbook.createSheet( "人力资源统计" );

		// 设置列宽
		sheet.setColumnWidth( 0, 3500 );
		sheet.setColumnWidth(1, 9000);
		sheet.setColumnWidth(2, 4000);
		HSSFPrintSetup printSetup = sheet.getPrintSetup();
		printSetup.setPaperSize( HSSFPrintSetup.A4_PAPERSIZE ); // 纸张
		sheet.setDisplayGridlines( false );
		sheet.setPrintGridlines( false );
		sheet.setMargin( HSSFSheet.TopMargin, (double) 0.1 ); // 上边距
		sheet.setMargin( HSSFSheet.BottomMargin, (double) 0.1 ); // 下边距
		sheet.setMargin( HSSFSheet.LeftMargin, (double) 0.1 ); // 左边距
		sheet.setMargin( HSSFSheet.RightMargin, (double) 0.1 ); // 右边距

		// 设置字体  20号楷体居中
		HSSFFont headfont = workbook.createFont();
		headfont.setFontName( "楷体" );
		headfont.setFontHeightInPoints( (short) 20 );// 字体大小
		HSSFCellStyle headstyle = workbook.createCellStyle();
		headstyle.setFont( headfont );
		headstyle.setAlignment( HorizontalAlignment.CENTER );//水平居中
		headstyle.setVerticalAlignment( VerticalAlignment.CENTER );//垂直居中
		headstyle.setLocked( true );
		headstyle.setWrapText( true );// 自动换行

		//12号 居中
		HSSFFont columnHeadFont = workbook.createFont();
		columnHeadFont.setFontName( "宋体" );
		columnHeadFont.setFontHeightInPoints( (short) 12 );
		HSSFCellStyle columnHeadStyle = workbook.createCellStyle();
		columnHeadStyle.setFont( columnHeadFont );
		columnHeadStyle.setAlignment( HorizontalAlignment.CENTER );//水平居中
		columnHeadStyle.setVerticalAlignment( VerticalAlignment.CENTER );//垂直居中
		columnHeadStyle.setLocked( true );
		columnHeadStyle.setWrapText( true );
		columnHeadStyle.setBorderBottom( BorderStyle.THIN ); //下边框
		columnHeadStyle.setBorderLeft( BorderStyle.THIN );//左边框
		columnHeadStyle.setBorderTop( BorderStyle.THIN );//上边框
		columnHeadStyle.setBorderRight( BorderStyle.THIN );//右边框

		//10号 居中
		HSSFFont font = workbook.createFont();
		font.setFontName( "宋体" );
		font.setFontHeightInPoints( (short) 10 );
		HSSFCellStyle centerstyle = workbook.createCellStyle();
		centerstyle.setFont( font );
		centerstyle.setAlignment( HorizontalAlignment.CENTER );//水平居中
		centerstyle.setVerticalAlignment( VerticalAlignment.CENTER );//垂直居中
		centerstyle.setWrapText( true );    // 自动换行
		centerstyle.setBorderBottom( BorderStyle.THIN ); //下边框
		centerstyle.setBorderLeft( BorderStyle.THIN );//左边框
		centerstyle.setBorderTop( BorderStyle.THIN );//上边框
		centerstyle.setBorderRight( BorderStyle.THIN );//右边框

		//12号 居左
		HSSFFont liftfont = workbook.createFont();
		liftfont.setFontName( "宋体" );
		liftfont.setFontHeightInPoints( (short) 12 );
		HSSFCellStyle leftstyle = workbook.createCellStyle();
		leftstyle.setFont( liftfont );
		leftstyle.setAlignment( HorizontalAlignment.LEFT );//水平居左
		leftstyle.setVerticalAlignment( VerticalAlignment.CENTER );//垂直居中
		leftstyle.setWrapText( true );
		leftstyle.setBorderBottom( BorderStyle.THIN ); //下边框
		leftstyle.setBorderLeft( BorderStyle.THIN );//左边框
		leftstyle.setBorderTop( BorderStyle.THIN );//上边框
		leftstyle.setBorderRight( BorderStyle.THIN );//右边框
		sheet.setDefaultColumnWidth( 6 );

		//10号 居左
		HSSFFont liftfont10 = workbook.createFont();
		liftfont10.setFontName( "宋体" );
		liftfont10.setFontHeightInPoints( (short) 10 );
		HSSFCellStyle leftstyle10 = workbook.createCellStyle();
		leftstyle10.setFont( liftfont10 );
		leftstyle10.setAlignment( HorizontalAlignment.LEFT );//水平居左
		leftstyle10.setVerticalAlignment( VerticalAlignment.CENTER );//垂直居中
		leftstyle10.setWrapText( true );
		leftstyle10.setBorderBottom( BorderStyle.THIN ); //下边框
		leftstyle10.setBorderLeft( BorderStyle.THIN );//左边框
		leftstyle10.setBorderTop( BorderStyle.THIN );//上边框
		leftstyle10.setBorderRight( BorderStyle.THIN );//右边框
		sheet.setDefaultColumnWidth( 6 );

		//10号 居右
		HSSFFont rightfont10 = workbook.createFont();
		rightfont10.setFontName( "宋体" );
		rightfont10.setFontHeightInPoints( (short) 10 );
		HSSFCellStyle rightstyle10 = workbook.createCellStyle();
		rightstyle10.setFont( rightfont10 );
		rightstyle10.setAlignment( HorizontalAlignment.RIGHT );//水平居右
		rightstyle10.setVerticalAlignment( VerticalAlignment.CENTER );//垂直居中
		rightstyle10.setWrapText( true );
		rightstyle10.setBorderBottom( BorderStyle.THIN ); //下边框
		rightstyle10.setBorderLeft( BorderStyle.THIN );//左边框
		rightstyle10.setBorderTop( BorderStyle.THIN );//上边框
		rightstyle10.setBorderRight( BorderStyle.THIN );//右边框
		sheet.setDefaultColumnWidth( 6 );
		//创建第一行表头
		//**********************头部***************************************************************
		HSSFRow row01 = sheet.createRow( 0 );// 创建第一行
		row01.setHeight( (short) 800 );// 设置行高
		HSSFCell cell0 = row01.createCell( 0 );
		String deptId = parm.get("deptId").toString();
 		if ("1".equals(deptId)) {
			deptId = "4";
		} else if ("2".equals(deptId)) {
			deptId = "5";
		} else if ("4".equals(deptId)) {
			deptId = "6";
		}
		if(!("").equals(deptId) && deptId!=null){
			String deptName =  sysClient.getDeptName(Integer.parseInt(deptId));
			if (parm.get("startDate").equals(parm.get("endDate"))){
				cell0.setCellValue(new HSSFRichTextString(deptName+" "+parm.get("startDate") + "月 人力资源月报"));
			}else {
				cell0.setCellValue(new HSSFRichTextString(deptName + " " + parm.get("startDate") + "月 至 " + parm.get("endDate") + "月 人力资源月报"));
			}
		}else{
			if (parm.get("startDate").equals(parm.get("endDate"))){
				cell0.setCellValue(new HSSFRichTextString(parm.get("startDate") + "月 人力资源月报"));
			}else {
				cell0.setCellValue(new HSSFRichTextString(parm.get("startDate") + "月 至 " + parm.get("endDate") + "月 人力资源月报"));
			}
		}
		cell0.setCellStyle( headstyle );
		HSSFCell cell1 = row01.createCell(1);
		cell1.setCellValue("");//加内容到列中
		cell1.setCellStyle(centerstyle);//加上面定义的样式
		HSSFCell cell2 = row01.createCell(2);//加内容到列中
		cell2.setCellValue("");//加内容到列中
		cell2.setCellStyle(centerstyle);//加上面定义的样式
		for(int j = 0;j <= userListSize;j++) {  //列
//			第一行
			HSSFCell cell3 = row01.createCell(j + 2);//加内容到列中
			cell3.setCellValue("");//加内容到列中
			cell3.setCellStyle(centerstyle);//加上面定义的样式
		}
		sheet.addMergedRegion( new CellRangeAddress( 0, 0, 0, userListSize + 3 ) );

		HSSFRow row02  = sheet.createRow(1);//第二行
		row02.setHeightInPoints(50);
		HSSFCell cell01 = row02.createCell(0);
		cell01.setCellValue("项目编号");//加内容到列中
		cell01.setCellStyle(centerstyle);//加上面定义的样式
		HSSFCell cell02 = row02.createCell(1);
		cell02.setCellValue("项目名称");//加内容到列中
		cell02.setCellStyle(centerstyle);//加上面定义的样式
		HSSFCell cell03 = row02.createCell(2);//加内容到列中
		cell03.setCellValue("部门");//加内容到列中
		cell03.setCellStyle(centerstyle);//加上面定义的样式

		String valueString = "";
		String hrdata = "";
		for(int j = 0;j < userListSize;j++) {  //列
//			第一行
			HSSFCell cell04 = row02.createCell(j + 3);//遍历列  前几列已经有数据
			valueString = userList.get(j).getRealname();
			cell04.setCellValue(valueString);//加内容到列中
			cell04.setCellStyle(centerstyle);//加上面定义的样式
		}
		HSSFCell cell05 = row02.createCell(userListSize+3);//加内容到列中
		cell05.setCellValue("项目人力资源统计");//加内容到列中
		cell05.setCellStyle(centerstyle);//加上面定义的样式

		Double sum=0.00;  //所有行数值相加的总值
		for (int i = 0;i < projectListSise; i++) {  //行
			HSSFRow row  = sheet.createRow(i+2);
			//前三列为项目信息
			HSSFCell cell001 = row.createCell(0);
			cell001.setCellValue(projectList.get(i).get("code") == null ? "":projectList.get(i).get("code")+"");//加内容到列中
			cell001.setCellStyle(centerstyle);//加上面定义的样式
			HSSFCell cell002 = row.createCell(1);
			cell002.setCellValue(projectList.get(i).get("name") == null ? "":projectList.get(i).get("name")+"");//加内容到列中
			cell002.setCellStyle(centerstyle);//加上面定义的样式
			HSSFCell cell003 = row.createCell(2);
			cell003.setCellValue(projectList.get(i).get("deptname") == null ? "":projectList.get(i).get("deptname")+"");//加内容到列中
			cell003.setCellStyle(centerstyle);//加上面定义的样式
//		每个项目的所有人力资源
			String pid = projectList.get(i).get("id").toString();
			parm.put("pId",pid);

			Double hrdataSum=0.00;  //每行总值
			for(int j = 0;j < userListSize;j++) {  //列
				parm.put("userId",userList.get(j).getAccount());
				List<Map<String, Object>>  hrDataList = projectMapper.getHrData(parm);

				if (hrDataList.size() > 0 ){
					 	hrdata =  "0.0".equals(hrDataList.get(0).get("hrdata").toString()) ? "":hrDataList.get(0).get("hrdata").toString();
				}else {
					hrdata = "";
				}
				HSSFCell cell004 = row.createCell(j+3);//遍历列  前几列已经有数据
				Boolean isNum = false;//data是否为数值型
				Boolean isInteger=false;//data是否为整数
				Boolean isPercent=false;//data是否为百分数
				if (hrdata != null || "".equals(hrdata)) {
					//判断data是否为数值型
					isNum = hrdata.toString().matches("^(-?\\d+)(\\.\\d+)?$");
					//判断data是否为整数（小数部分是否为0）
					isInteger=hrdata.toString().matches("^[-\\+]?[\\d]*$");
					//判断data是否为百分数（是否包含“%”）
					isPercent=hrdata.toString().contains("%");
				}
				//如果单元格内容是数值类型，涉及到金钱（金额、本、利），则设置cell的类型为数值型，设置data的类型为数值类型
				if (isNum && !isPercent) {
					HSSFDataFormat df = workbook.createDataFormat(); // 此处设置数据格式
					if (isInteger) {
						centerstyle.setDataFormat(df.getBuiltinFormat("#,#0"));//数据格式只显示整数
					}else{
						centerstyle.setDataFormat(df.getBuiltinFormat("#,##0.00"));//保留两位小数点
					}
					// 设置单元格格式
					cell004.setCellStyle(centerstyle);
					// 设置单元格内容为double类型
					cell004.setCellValue(Double.parseDouble(hrdata.toString()));
				} else {
					cell004.setCellStyle(centerstyle);
					// 设置单元格内容为字符型
					cell004.setCellValue(hrdata.toString());
				}

				if (!"".equals(hrdata.toString())&&hrdata.toString()!=null){
					hrdataSum=hrdataSum+Double.parseDouble(hrdata.toString()); //遍历添加每行总和
				}
			}
			HSSFCell cell005 = row.createCell(userListSize+3);//遍历列  前几列已经有数据
			cell005.setCellStyle(centerstyle);
			cell005.setCellValue(String.format("%.2f",hrdataSum));

			sum=sum+hrdataSum; //每行总值相加
		}
		Cell cell;// 单元格
		String colString;//长度转成ABC后的列
		String sumString;//求和公式

		HSSFRow rowx  = sheet.createRow(projectListSise + 2);//最后一行
		HSSFCell cell005 = rowx.createCell(userListSize + 3); //最后一行的最后建立一个单元格，放入所有数据总和
		cell005.setCellStyle(centerstyle);

		cell005.setCellValue(String.format("%.2f",sum));
		for (int k = 0; k < userListSize + 3; k++) {   //  从第3列开始每列都执行求和操作 因此i=3
			cell = rowx.createCell(k);// 创建单元格
			cell.setCellStyle(centerstyle);// 设置单元格样式
			colString = CellReference.convertNumToColString(k);  //长度转成ABC列
			//求和公式 求i9至i12单元格的总和
			sumString = "SUM(" + colString + "3:" + colString + Integer.valueOf(projectListSise+2)+ ")";
			if (k  == 0) {
				cell.setCellValue("累计有效工作天数:");
			}else{
				cell.setCellFormula(sumString);// 把公式塞入合计列
			}
		}
		sheet.addMergedRegion( new CellRangeAddress( projectListSise+2, projectListSise+2, 0,  2 ) );
		return workbook;
	}

	@Override
	public List<Integer> getZtDeptId(String deptName) {
		return humanUserMapper.getZtDeptId(deptName);
	}
}
